﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using EuphoricNation.Util;

namespace EuphoricNation.Rewrite
{
    /// <summary>
    /// Redirects for site
    /// </summary>
    public sealed class Redirects
    {
        #region Singleton pattern
        static readonly Redirects _instance = new Redirects();

        static Redirects()
        {
        }

        public Redirects()
        {
        }

        public static Redirects Current
        {
            get
            {
                return _instance;
            }
        }
        #endregion

        private Dictionary<string, Redirect> _redirects = new Dictionary<string, Redirect>();

        /// <summary>
        /// Redirects registered with the site
        /// </summary>
        public Dictionary<string, Redirect> RedirectCollection
        {
            get { return _redirects; }
        }

        /// <summary>
        /// Add a new redirect to the manager
        /// </summary>
        /// <param name="redirect">Redirect to add</param>
        public void AddRedirect(Redirect redirect)
        {
            if (!_redirects.ContainsKey(redirect.FromURL))
                _redirects.Add(redirect.FromURL, redirect);
        }

        /// <summary>
        /// Get the redirect for a specific path
        /// </summary>
        /// <param name="path">Path</param>
        /// <returns>Matching redirect</returns>
        public Redirect GetRedirect(string path)
        {
            path = path.ToLower();

            foreach (KeyValuePair<string, Redirect> pair in _redirects)
            {
                if (pair.Key.ToLower() == path)
                    return pair.Value;
            }
                
            return null;
        }
    }
}
